<!DOCTYPE html>
<html lang="zh" xml:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>调试页面 - 物联网调试管理系统</title>
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/tabler/tabler.min.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/tabler/tabler.min.css}" />
    <link
      rel="stylesheet"
      th:href="@{/statics/bootstrap/table/bootstrap-table.min.css}"
      type="text/css"
    />
    <script
      th:src="@{/statics/bootstrap/table/bootstrap-table.min.js}"
    ></script>
    <script
      th:src="@{/statics/bootstrap/table/bootstrap-table-zh-CN.min.js}"
    ></script>
    <link rel="stylesheet" th:href="@{/statics/system/common.css}" />

    <!-- 引入 layui.css -->
    <link rel="stylesheet" th:href="@{/statics/layui/layui.css}" />
    <!-- 引入 layui.js -->
    <script th:src="@{/statics/layui/layui.js}"></script>
    <script th:src="@{/statics/system/common.js}"></script>
    <script th:src="@{/statics/system/pages/menu.js}"></script>
    <script th:src="@{/statics/system/utils.js}"></script>
  </head>
  <body>
    <div class="page">
      <div th:replace="common/header :: header"></div>

      <div class="page-wrapper">
        <div class="page-header d-print-none">
          <div class="container-xxl">
            <div class="row g-2 align-items-center">
              <div class="col">
                <!-- Page pre-title -->
                <div class="page-pretitle">物联网调试管理后台</div>
                <h2 class="page-title">调试页面管理</h2>
              </div>
              <div class="col-auto ms-auto d-print-none">
                <div class="btn-list">
                  <div class="btn-list">
                    <button
                      class="btn btn-primary d-none d-sm-inline-block"
                      onclick="addPage()"
                    >
                      <svg
                        class="icon"
                        fill="none"
                        height="24"
                        stroke="currentColor"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        viewBox="0 0 24 24"
                        width="24"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          d="M0 0h24v24H0z"
                          fill="none"
                          stroke="none"
                        ></path>
                        <path d="M12 5l0 14"></path>
                        <path d="M5 12l14 0"></path>
                      </svg>
                      新建调试页面
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="page-body">
          <div class="container-xxl">
            <div class="row row-deck row-cards">
              <div class="col-12">
                <div class="spinner-border" id="list_refresh"></div>
                <div class="card" id="card">
                  <div class="card-body" style="display: inline-block">
                    <div class="row">
                      <div class="col-2">
                        <div id="tree"></div>
                      </div>
                      <div class="col-10">
                        <div class="table-responsive" style="height: 560px">
                          <table
                            class="table table-vcenter"
                            id="page_list"
                            lay-filter="page_list"
                          ></table>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div id="modal-showinfo" style="display: none">
        <div class="layui-card">
          <div class="layui-card-body">
            <fieldset class="layui-elem-field" style="margin-top: 10px">
              <legend>MQTT主机</legend>
              <div class="layui-field-box">
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">连接协议</div>
                    <div class="layui-card-body">
                      <span
                        class="layui-badge layui-bg-green"
                        id="view_protocol"
                      ></span>
                    </div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">服务器地址</div>
                    <div class="layui-card-body" id="view_server"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">端口</div>
                    <div class="layui-card-body" id="view_port"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">用户名</div>
                    <div class="layui-card-body" id="view_username"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">密码</div>
                    <div class="layui-card-body" id="view_password"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">发布订阅</div>
                    <div class="layui-card-body" id="view_sendTopic"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">接收订阅</div>
                    <div class="layui-card-body" id="view_receiveTopic"></div>
                  </div>
                </div>
                <div class="layui-col-md6">
                  <div class="layui-card">
                    <div class="layui-card-header">QoS</div>
                    <div class="layui-card-body" id="view_qos"></div>
                  </div>
                </div>
              </div>
            </fieldset>

            <div class="layui-table" style="margin-top: 20px">
              <table class="layui-table" id="params_table"></table>
            </div>
          </div>
        </div>
      </div>

      <div id="modal-edit" style="display: none">
        <blockquote class="layui-elem-quote" style="margin: 25px">
          可选择现有的MQTT服务器，也可在下方自定义MQTT服务器信息，自定义MQTT服务器将会保存到MQTT服务器列表中。
        </blockquote>
        <div class="layui-card">
          <input id="edit_id" type="hidden" />
          <div class="layui-card-body" style="display: none">
            <div class="layui-row layui-col-space15">
              <div class="layui-col-md6">
                <div class="layui-form-item">
                  <label class="layui-form-label">访问地址</label>
                  <div class="layui-input-group">
                    <button class="layui-btn" id="edit_reseturl" type="button">
                      生成
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="layui-row" style="padding: 20px">
            <div class="layui-col-md6" style="width: auto">
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >页面名称</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="edit_name"
                    name="edit_name"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >访问地址</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="edit_url"
                    name="edit_url"
                    readonly
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认发送Topic</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="edit_mqtt_sendTopic"
                    name="edit_mqtt_sendTopic"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认订阅Topic</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="edit_mqtt_receiveTopic"
                    name="edit_mqtt_receiveTopic"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >客户分组</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="edit_customer"
                    style="width: 200px"
                    name="edit_customer"
                  ></select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认QoS</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="edit_mqtt_qos"
                    name="edit_mqtt_qos"
                    style="width: 200px"
                    required
                  >
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                  </select>
                </div>
              </div>
            </div>

            <div class="layui-col-md6">
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >MQTT主机</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="edit_token"
                    name="edit_token"
                  ></select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >连接协议</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="edit_protocol"
                    style="width: 300px"
                    name="edit_protocol"
                    required
                  >
                    <option value="1">TCP</option>
                    <option selected value="2">WebSocket</option>
                  </select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >服务器地址</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="edit_server"
                    name="edit_server"
                    style="width: 300px"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >服务器端口</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="edit_port"
                    name="edit_port"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >用户名</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="edit_username"
                    name="edit_username"
                    placeholder="请输入"
                    type="text"
                  />
                </div>
              </div>

              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >密码</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="edit_password"
                    name="edit_password"
                    placeholder="请输入"
                    type="text"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="layui-card-footer" style="text-align: center">
          <button
            class="layui-btn layui-btn-primary"
            onclick="layer.closeAll()"
            type="button"
          >
            取消
          </button>
          <button
            class="layui-btn layui-btn-normal"
            id="edit_save"
            onclick="submitUpdate()"
            type="button"
          >
            保存
          </button>
        </div>
      </div>

      <div id="modal-add" style="display: none">
        <blockquote class="layui-elem-quote" style="margin: 25px">
          可选择现有的MQTT服务器，也可在下方自定义MQTT服务器信息，自定义MQTT服务器将会保存到MQTT服务器列表中。
        </blockquote>
        <div class="layui-card">
          <input id="add_id" type="hidden" />
          <div class="layui-card-body" style="display: none">
            <div class="layui-row layui-col-space15">
              <div class="layui-col-md6">
                <div class="layui-form-item">
                  <label class="layui-form-label">访问地址</label>
                  <div class="layui-input-group">
                    <button class="layui-btn" id="add_reseturl" type="button">
                      生成
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="layui-row" style="padding: 20px">
            <div class="layui-col-md6" style="width: auto">
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >页面名称</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="add_name"
                    name="add_name"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >访问地址</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="add_url"
                    name="add_url"
                    readonly
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认发送Topic</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="add_mqtt_sendTopic"
                    name="add_mqtt_sendTopic"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认订阅Topic</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    style="width: 200px"
                    id="add_mqtt_receiveTopic"
                    name="add_mqtt_receiveTopic"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >客户分组</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="add_customer"
                    style="width: 200px"
                    name="add_customer"
                  >
                    <option value="0">未分配</option>
                  </select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 120px"
                  >默认QoS</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="add_mqtt_qos"
                    name="add_mqtt_qos"
                    style="width: 200px"
                    required
                  >
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                  </select>
                </div>
              </div>
            </div>

            <div class="layui-col-md6">
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >MQTT主机</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="add_token"
                    name="add_token"
                  ></select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >连接协议</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <select
                    class="layui-select"
                    id="add_protocol"
                    style="width: 300px"
                    name="add_protocol"
                    required
                  >
                    <option value="1">TCP</option>
                    <option selected value="2">WebSocket</option>
                  </select>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >服务器地址</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="add_server"
                    name="add_server"
                    style="width: 300px"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >服务器端口</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="add_port"
                    name="add_port"
                    placeholder="请输入"
                    required
                    type="text"
                  />
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >用户名</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="add_username"
                    name="add_username"
                    placeholder="请输入"
                    type="text"
                  />
                </div>
              </div>

              <div class="layui-form-item">
                <label class="layui-form-label" style="width: 110px"
                  >密码</label
                >
                <div class="layui-input-block" style="margin-left: 120px">
                  <input
                    class="layui-input"
                    id="add_password"
                    name="add_password"
                    placeholder="请输入"
                    type="text"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="layui-card-footer" style="text-align: center">
          <button
            class="layui-btn layui-btn-primary"
            onclick="layer.closeAll()"
            type="button"
          >
            取消
          </button>
          <button
            class="layui-btn layui-btn-normal"
            id="add_save"
            onclick="submitAdd()"
            type="button"
          >
            保存
          </button>
        </div>
      </div>

      <div id="modal-message" style="display: none">
        <div class="layui-card">
          <input id="param_page_id" type="hidden" />
          <div class="layui-card-body">
            <div class="layui-form">
              <div class="layui-form-item">
                <label class="layui-form-label">参数</label>
                <div class="layui-input-block">
                  <textarea class="layui-textarea" id="message_add" type="text" placeholder="请输入调试参数 一行一个&#10;如果输入多行，则为批量发送，默认间隔100ms"></textarea>
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">按钮</label>
                <div class="layui-input-block">
                  <input class="layui-input" id="button_add" type="text" placeholder="请输入按钮名称" />
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-input-block">
                  <button class="layui-btn" onclick="submitAddMessage()" type="button">
                    添加参数
                  </button>
                </div>
              </div>
            </div>
            <div class="fixed-table-container" style="padding-bottom: 0px; height: auto">
              <script id="barDemo" type="text/html">
                <div class="layui-clear-space">
                  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
                </div>
              </script>
              <table class="layui-hide" id="test" lay-filter="test"></table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
  <script th:inline="none">
    //菜单class追加属性
    $(function () {
      $("#menu_pages").addClass("active");
      $("#list_refresh").hide();
    });

    //渲染数据
    let table;
    layui.use(["table", "layer"], function () {
      table = layui.table;
      var layer = layui.layer;

      var inst = table.render({
        elem: "#page_list",
        url: "/page/list",
        method: "GET",
        page: true,
        height: 540,
        request: {
          pageName: "pageNum",
          limitName: "pageSize",
        },
          where: {
              commonPage: 0,
          },
        parseData: function (res) {
          return {
            code: res.code === 200 ? 0 : 1,
            msg: res.msg,
            count: res.data.total,
            data: res.data.rows,
          };
        },
        cols: [
          [
            {
              field: "pageName",
              title: "页面名称",
              align: "center",
              templet: function (d) {
                return (
                  '<a class="page_a" href="/mq/' +
                  d.pageUrl +
                  '" target="_blank">' +
                  d.pageName +
                  "</a>"
                );
              },
            },
            {
              field: "pageUrl",
              title: "访问地址(点击复制)",
              align: "center",
              templet: function (d) {
                return (
                  '<span class="url" onclick="copyUrl(this)" data-clipboard-text="' +
                  d.pageUrl +
                  '">' +
                  d.pageUrl +
                  "</span>"
                );
              },
            },
            {
              field: "token",
              title: "Token",
              align: "center",
              templet: function (d) {
                return (
                  '<div style="display: flex;flex-direction: column">' +
                  '<span style="font-weight: bolder">' +
                  d.settings.mqttServer +
                  ":" +
                  d.settings.mqttPort +
                  "</span>" +
                  '<span style="font-size: 12px;color: #999999">' +
                  d.settings.name +
                  "</span>" +
                  '<span style="font-size: 12px;color: #999999">' +
                  d.settings.token +
                  "</span>" +
                  "</div>"
                );
              },
            },
            {
              field: "sendTopic",
              title: "发布订阅",
              align: "center",
              hide: true,
            },
            {
              field: "receiveTopic",
              title: "Topic",
              align: "center",
              templet: function (d) {
                return (
                  '<div style="display: flex;flex-direction: column">' +
                  '<span style="font-size: 12px;color: #999999">发布：' +
                  d.sendTopic +
                  "</span>" +
                  '<span style="font-size: 12px;color: #999999">接收：' +
                  d.receiveTopic +
                  "</span>" +
                  "</div>"
                );
              },
            },
            {
              field: "customer",
              title: "客户",
              align: "center",
              templet: function (d) {
                if (
                  d.customer === null ||
                  d.customer === "" ||
                  d.customer === undefined
                ) {
                  return '<span class="layui-badge layui-bg-gray">未分配</span>';
                } else {
                  return (
                    '<span class="layui-badge layui-bg-green">' +
                    d.customer.name +
                    "</span>"
                  );
                }
              },
            },
            {
              title: "操作",
              align: "center",
              templet: function (d) {
                return `
                            <div style="display: flex; flex-direction: column;">
                                <div>

                                    <button onclick="editInfo(${d.id})" class="layui-btn layui-btn-normal layui-btn-xs">编辑</button>
                                    <button onclick="showMessage(${d.id})" class="layui-btn layui-btn-warm layui-btn-xs">参数</button>
                                </div>
                                <div style="margin-top: 5px;">
                                    <button onclick="copyPage(${d.id})" class="layui-btn layui-btn-primary layui-btn-xs">复制</button>
                                    <button onclick="deletePage(${d.id})" class="layui-btn layui-btn-danger layui-btn-xs">删除</button>
                                </div>
                            </div>
                        `;
              },
            },
          ],
        ],
      });

      // 实例对象成员
      inst.config; // 当前表格配置属性
      inst.resize(); // 对当前表格重新适配尺寸
      inst.setColsWidth(); // 对当前表格重新分配列宽

      //监听工具条
      table.on("tool(test)", function (obj) {
        var data = obj.data;
        if (obj.event === "del") {
          layer.confirm("真的删除行么", function (index) {
            submitDeleteMessage(data.id);
            layer.close(index);
          });
        }
      });

      layui.use("tree", function () {
        const tree = layui.tree;

        $.ajax({
          url: "/customer/list?pageNum=0&pageSize=0",
          type: "GET",
          dataType: "json",
          success: function (data) {
            //把name字段改成title
            let customerList = data.data.rows;
            for (let i = 0; i < customerList.length; i++) {
              customerList[i].title = customerList[i].name;
              delete customerList[i].name;
            }
            //渲染
            tree.render({
              elem: "#tree",
              onlyIconControl: true,
              data: [
                {
                  title: "全部客户",
                  spread: true,
                  children: customerList,
                },
              ],
              click: function (obj) {
                console.log(obj.data); //得到当前点击的节点数据
                var url = "/page/list";
                if (obj.data.id === undefined) {
                  //全部客户
                  url = "/page/list";
                } else {
                  //单独的客户
                  url = "/page/list?customerId=" + obj.data.id;
                }

                table.reload("page_list", {
                  url: url,
                  page: {
                    curr: 1, // 重新从第 1 页开始
                  },
                });
              },
            });
          },
        });
      });
    });

    // 复制页面
    function copyPage(id) {
      layer.confirm("确定复制此页面吗？", function (index) {
        $.ajax({
          url: "/page/copy/" + id,
          type: "POST",
          dataType: "json",
          success: function (data) {
            if (data.code === 200) {
              layer.msg("复制成功", { icon: 1 });
              table.reload("page_list");
            } else {
              layer.msg(data.msg, { icon: 2 });
            }
          },
        });
        layer.close(index);
      });
    }

    function editInfo(row) {
      // 获取客户列表
      $.ajax({
        url: "/customer/list?pageNum=0&pageSize=0",
        type: "GET",
        dataType: "json",
        success: function (data) {
          let customerList = data.data.rows;
          let customerHtml = '<option value="0">未分配</option>';
          customerList.forEach((customer) => {
            customerHtml += `<option value="${customer.id}">${customer.name}</option>`;
          });
          $("#edit_customer").html(customerHtml);

          // 在获取客户列表成功后，获取页面信息
          $.ajax({
            url: `/page/info/${row}`,
            type: "GET",
            dataType: "json",
            success: function (data) {
              let params = data.data;
              $("#edit_id").val(params.id);
              $("#edit_name").val(params.pageName);
              $("#edit_url").val(params.pageUrl);
              $("#edit_mqtt_sendTopic").val(params.sendTopic);
              $("#edit_mqtt_receiveTopic").val(params.receiveTopic);
              $("#edit_filename").val(params.pageFileName);
              $("#edit_customer").val(
                params.customer ? params.customer.id : "0"
              );
              $("#edit_batch_send").val(params.batchSend);
              $("#edit_batch_command").val(params.batchCommand);
              $("#edit_batch_delay").val(params.batchDelay);

              // 获取token列表
              $.ajax({
                url: "/nmqs/list?pageNum=0&pageSize=0",
                type: "GET",
                dataType: "json",
                success: function (data) {
                  let tokenList = data.data.rows;
                  let tokenHtml = tokenList
                    .map(
                      (token) =>
                        `<option value="${token.id}">${token.name} --- ${token.token} --- ${token.mqttServer}:${token.mqttPort}</option>`
                    )
                    .join("");

                  //在最前方插入一个 自定义
                  tokenHtml =
                    '<option value="0">自定义（添加临时MQTT服务器）</option>' +
                    tokenHtml;

                  $("#edit_token").html(tokenHtml);
                  $("#edit_token").val(params.nmqsTokenId);

                  // 设置MQTT主机信息
                  $("#edit_protocol").val(params.settings.protocol);
                  $("#edit_server").val(params.settings.mqttServer);
                  $("#edit_port").val(params.settings.mqttPort);
                  $("#edit_username").val(params.settings.mqttUsername);
                  $("#edit_password").val(params.settings.mqttPassword);

                  if ($("#edit_token").val() !== "0") {
                    $("#edit_protocol").prop("disabled", true);
                    $("#edit_server").attr("readonly", "readonly");
                    $("#edit_port").attr("readonly", "readonly");
                    $("#edit_username").attr("readonly", "readonly");
                    $("#edit_password").attr("readonly", "readonly");
                  }

                  layer.open({
                    type: 1,
                    area: ["900px", "600px"],
                    title: "编辑调试页面",
                    content: $("#modal-edit"),
                  });
                },
              });
            },
          });
        },
      });

      $("#edit_reseturl").on("click", function () {
        $("#edit_url").val(randomString(12));
      });

      //nmqsTokenID改变时
      $("#edit_token").on("change", function () {
        let tokenID = $(this).val();
        if (tokenID == "0") {
          //全部解除readonly
          $("#edit_protocol").prop("disabled", false);
          $("#edit_server").removeAttr("readonly");
          $("#edit_port").removeAttr("readonly");
          $("#edit_username").removeAttr("readonly");
          $("#edit_password").removeAttr("readonly");
        } else {
          //加上readonly
          $("#edit_protocol").prop("disabled", true);
          $("#edit_server").attr("readonly", "readonly");
          $("#edit_port").attr("readonly", "readonly");
          $("#edit_username").attr("readonly", "readonly");
          $("#edit_password").attr("readonly", "readonly");

          //获取token信息
          $.ajax({
            url: "/nmqs/info/" + tokenID,
            type: "GET",
            dataType: "json",
            success: function (data) {
              let token = data.data;
              $("#edit_protocol").val(token.protocol);
              $("#edit_server").val(token.mqttServer);
              $("#edit_port").val(token.mqttPort);
              $("#edit_username").val(token.mqttUsername);
              $("#edit_password").val(token.mqttPassword);
            },
          });
        }
      });
    }

    function submitUpdate() {
      const id = $("#edit_id").val();
      const name = $("#edit_name").val();
      const url = $("#edit_url").val();
      const token = $("#edit_token").val();
      const sendTopic = $("#edit_mqtt_sendTopic").val();
      const receiveTopic = $("#edit_mqtt_receiveTopic").val();
      const customerId = $("#edit_customer").val();
      const filename = $("#edit_filename").val();

      const protocol = $("#edit_protocol").val();
      const server = $("#edit_server").val();
      const port = $("#edit_port").val();
      const username = $("#edit_username").val();
      const password = $("#edit_password").val();

      const fields = [
        { value: name, message: "页面名称不能为空" },
        { value: url, message: "页面地址不能为空" },
        { value: token, message: "token不能为空" },
        { value: sendTopic, message: "发送主题不能为空" },
        { value: receiveTopic, message: "接收主题不能为空" },
      ];

      const fieldsServer = [
        { value: protocol, message: "连接协议不能为空" },
        { value: server, message: "服务器地址不能为空" },
        { value: port, message: "端口不能为空" },
      ];

      for (const field of fields) {
        if (isBlank(field.value)) {
          layer.msg(field.message);
          return;
        }
      }

      if (token === "0") {
        for (const field of fieldsServer) {
          if (isBlank(field.value)) {
            layer.msg(field.message);
            return;
          }
        }

        // 验证端口 和 范围
        if (port < 0 || port > 65535) {
          layer.msg("端口范围为0-65535");
          return;
        }
      }

      const data = {
        id,
        pageName: name,
        pageUrl: url,
        nmqsTokenId: token,
        sendTopic,
        receiveTopic,
        pageFileName: filename,
        customerId: customerId,
        protocol: protocol,
        mqttServer: server,
        mqttPort: port,
        mqttUsername: username,
        mqttPassword: password,
      };

      $.ajax({
        url: "/page/update",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (response) {
          if (response.code === 200) {
            layer.msg("修改成功");
            layer.closeAll();
            table.reload("page_list");
          } else {
            layer.msg("修改失败");
          }
        },
      });
    }

    function showMessage(row) {
      $("#param_page_id").val(row);

      openParamMenu(row);
    }

    function submitDeleteMessage(row) {
      let url = "/page/param/delete/" + row;
      $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        success: function (data) {
          if (data.code === 200) {
            layer.msg("删除成功");

            table.reload("test");
          } else {
            layer.msg("删除失败");
          }
        },
      });
    }

    function submitAddMessage() {
      let pageId = $("#param_page_id").val();
      let message = $("#message_add").val();
      let button = $("#button_add").val();

      let data = {
        message: message,
        button: button,
      };

      $.ajax({
        url: "/page/" + pageId + "/param/add",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (data) {
          if (data.code === 200) {
            layer.msg("添加成功");

            table.reload("test");

            $("#message_add").val("");
            $("#button_add").val("");
          } else {
            layer.msg("添加失败");
          }
        },
      });
    }

    function addPage() {
      // 清空数据
      $(
        "#add_name, #add_url, #add_filename, #add_mqtt_sendTopic, #add_mqtt_receiveTopic"
      ).val("");

      // 获取token列表
      $.getJSON("/nmqs/list?pageNum=0&pageSize=0", function (data) {
        const tokenList = data.data.rows;
        let tokenHtml = tokenList
          .map(
            (token) =>
              `<option value="${token.id}">${token.name} --- ${token.token} --- ${token.mqttServer}:${token.mqttPort}</option>`
          )
          .join("");

        //在最前方插入一个 自定义
        tokenHtml =
          '<option value="0">自定义（添加临时MQTT服务器）</option>' + tokenHtml;

        $("#add_token").html(tokenHtml);
      });

      // 获取客户列表
      $.getJSON("/customer/list?pageNum=0&pageSize=0", function (data) {
        const customerList = data.data.rows;
        let customerHtml = customerList
          .map(
            (customer) =>
              `<option value="${customer.id}">${customer.name}</option>`
          )
          .join("");

        //设置默认未分配
        customerHtml = '<option value="0">未分配</option>' + customerHtml;

        $("#add_customer").html(customerHtml);
      });

      // 设置随机访问地址
      $("#add_url").val(randomString(12));

      // 打开弹出层
      layer.open({
        type: 1,
        area: ["900px", "600px"],
        title: "添加调试页面",
        content: $("#modal-add"),
      });

      $("#add_token").on("change", function () {
        let tokenID = $(this).val();
        if (tokenID == "0") {
          //全部解除readonly
          $("#add_protocol").prop("disabled", false);
          $("#add_server").removeAttr("readonly");
          $("#add_port").removeAttr("readonly");
          $("#add_username").removeAttr("readonly");
          $("#add_password").removeAttr("readonly");
        } else {
          //加上readonly
          $("#add_protocol").prop("disabled", true);
          $("#add_server").attr("readonly", "readonly");
          $("#add_port").attr("readonly", "readonly");
          $("#add_username").attr("readonly", "readonly");
          $("#add_password").attr("readonly", "readonly");

          //获取token信息
          $.ajax({
            url: "/nmqs/info/" + tokenID,
            type: "GET",
            dataType: "json",
            success: function (data) {
              let token = data.data;
              $("#add_protocol").val(token.protocol);
              $("#add_server").val(token.mqttServer);
              $("#add_port").val(token.mqttPort);
              $("#add_username").val(token.mqttUsername);
              $("#add_password").val(token.mqttPassword);
            },
          });
        }
      });
    }

    function submitAdd() {
      const fields = [
        { selector: "#add_name", message: "页面名称不能为空" },
        { selector: "#add_url", message: "页面url不能为空" },
        { selector: "#add_token", message: "token不能为空" },
        { selector: "#add_customer", message: "客户不能为空" },
        { selector: "#add_mqtt_sendTopic", message: "发送主题不能为空" },
        { selector: "#add_mqtt_receiveTopic", message: "接收主题不能为空" },
      ];

      for (const field of fields) {
        if (isBlank($(field.selector).val())) {
          layer.msg(field.message);
          return;
        }

        //验证MQTT主机
        if ($("#add_token").val() === "0") {
          const fieldsServer = [
            { selector: "#add_protocol", message: "连接协议不能为空" },
            { selector: "#add_server", message: "服务器地址不能为空" },
            { selector: "#add_port", message: "端口不能为空" },
          ];

          for (const field of fieldsServer) {
            if (isBlank($(field.selector).val())) {
              layer.msg(field.message);
              return;
            }
          }

          // 验证端口 和 范围
          if ($("#add_port").val() < 0 || $("#add_port").val() > 65535) {
            layer.msg("端口范围为0-65535");
            return;
          }
        }
      }

      let data = {
        pageName: $("#add_name").val(),
        pageUrl: $("#add_url").val(),
        nmqsTokenId: $("#add_token").val(),
        sendTopic: $("#add_mqtt_sendTopic").val(),
        receiveTopic: $("#add_mqtt_receiveTopic").val(),
        pageFileName: $("#add_filename").val(),
        customerId: $("#add_customer").val(),
        protocol: $("#add_protocol").val(),
        mqttServer: $("#add_server").val(),
        mqttPort: $("#add_port").val(),
        mqttUsername: $("#add_username").val(),
        mqttPassword: $("#add_password").val(),
      };
      $.ajax({
        url: "/page/add",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (data) {
          if (data.code === 200) {
            layer.msg("添加成功");
            layer.closeAll();
            table.reload("page_list");
          } else {
            layer.msg(data.msg);
          }
        },
      });
    }

    function deletePage(row) {
      let url = "/page/delete/" + row;

      layer.confirm(
        "你确认要删除 ID:" + row + " 吗？",
        {
          btn: ["确认", "取消"], //按钮
        },
        function () {
          $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            success: function (data) {
              if (data.code === 200) {
                layer.msg("删除成功！", { icon: 1 });

                table.reload("page_list");
              } else {
                alert(data.msg);
              }
            },
          });
        },
        function () {
          layer.msg("已取消", { icon: 1 });
        }
      );
    }

    const copyUrl = async (element) => {
      //取data-clipboard-text的值，也就是需要复制的内容
      let ele = $(element);
      let val = ele.attr("data-clipboard-text");
      //拼接url
      let url =
        window.location.protocol + "//" + window.location.host + "/mq/" + val;
      if (navigator.clipboard && navigator.permissions) {
        await navigator.clipboard.writeText(url);
        layer.msg("复制成功");
      } else {
        const textArea = document.createElement("textArea");
        textArea.value = url;
        textArea.style.width = "0px";
        textArea.style.position = "fixed";
        textArea.style.left = "-999px";
        textArea.style.top = "10px";
        textArea.setAttribute("readonly", "readonly");
        document.body.appendChild(textArea);

        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        layer.msg("复制成功");
      }
    };
  </script>
  <style>
    .fixed-table-container {
      height: 500px;
      border: 1px solid #ddd;
    }

    #tree {
      height: 400px;
      overflow: auto;
    }

    .list-group-item {
      padding: 0.5rem 1rem;
    }

    .page_a:hover {
      color: #0a53be;
    }

    #modal-message tr td:nth-child(2) {
      width: 400px;
      word-break: break-all;
      text-align: left !important;
    }

    #modal-showinfo tr td:nth-child(2) {
      width: 400px;
      word-break: break-all;
      text-align: left !important;
    }

    .layui-card .layui-card-body .layui-table td {
      max-width: 100%;
    }
    .layui-table-cell {
      height: auto;
    }

    .url {
      cursor: pointer;
      color: #0a53be;
    }

    .url:hover {
      text-decoration: underline;
    }

    input[disabled] {
      background-color: #eee !important;
    }

    input[readonly] {
      background-color: #eee !important;
    }

    select[disabled] {
      background-color: #eee !important;
    }

    select[readonly] {
      background-color: #eee !important;
    }
  </style>
</html>
